package com.yungu.swift.system.sys.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.yungu.swift.assets.driver.model.dto.CarModelDto;
import com.yungu.swift.assets.driver.model.dto.CarModelValuationDto;
import com.yungu.swift.assets.driver.service.CarModelService;
import com.yungu.swift.assets.driver.service.CarModelValuationService;
import com.yungu.swift.assets.passenger.model.dto.PassengerRechargeCityDto;
import com.yungu.swift.assets.passenger.service.PassengerRechargeCityService;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.base.mapper.IMapper;
import com.yungu.swift.base.model.config.ServerConfig;
import com.yungu.swift.base.service.impl.BaseServiceImpl;
import com.yungu.swift.constants.CommonConstant;
import com.yungu.swift.lbs.model.vo.GeoVo;
import com.yungu.swift.lbs.service.LocationService;
import com.yungu.swift.system.config.ApplicationConfig;
import com.yungu.swift.system.marketing.dao.MarketingChannelMapper;
import com.yungu.swift.system.marketing.dao.MarketingGiftCityMapper;
import com.yungu.swift.system.marketing.dao.MarketingGiftMapper;
import com.yungu.swift.system.marketing.model.dto.MarketingChannelDto;
import com.yungu.swift.system.marketing.model.dto.MarketingGiftDto;
import com.yungu.swift.system.sys.dao.*;
import com.yungu.swift.system.sys.model.dto.*;
import com.yungu.swift.system.sys.model.param.AdminBusinessCityAddParam;
import com.yungu.swift.system.sys.model.vo.BusinessDetailVo;
import com.yungu.swift.system.sys.service.SysBusinessCityService;
import com.yungu.swift.system.sys.service.SysCityService;
import com.yungu.swift.system.sys.service.SysFenceService;
import com.yungu.swift.system.utils.PinyinUtils;
import com.yungu.swift.utils.DateUtils;
import com.yungu.swift.utils.MapUtils;
import com.yungu.swift.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.*;


/**
 * SystemBusinessCityServiceImpl
 **/
@Slf4j
@Service
public class SysBusinessCityServiceImpl extends BaseServiceImpl<SysBusinessCityDto> implements SysBusinessCityService {

    @Autowired
    private SysBusinessCityMapper sysBusinessCityMapper;
    @Autowired
    private SysBusinessOrganizationMapper sysBusinessOrganizationMapper;
    @Autowired
    private SysBusinessMapper sysBusinessMapper;
    @Autowired
    private SysCityService sysCityService;
    @Autowired
    private SysOpenAreaConfigMapper sysOpenAreaConfigMapper;
    @Autowired
    private SysAreaMapper sysAreaMapper;
    @Autowired
    private SysCityMapper sysCityMapper;
    @Autowired
    private SysAssignConfigMapper sysAssignConfigMapper;
    @Autowired
    private MarketingGiftMapper marketingGiftMapper;
    @Autowired
    private MarketingGiftCityMapper marketingGiftCityMapper;
    @Autowired
    private MarketingChannelMapper marketingChannelMapper;
    @Autowired
    private SysFenceService sysFenceService;

    @Reference
    private CarModelService carModelService;
    @Reference
    private CarModelValuationService carModelValuationService;
    @Reference
    private PassengerRechargeCityService passengerRechargeCityService;
    @Reference
    private LocationService locationService;


    @Override
    protected IMapper<SysBusinessCityDto> getMapper() {
        return sysBusinessCityMapper;
    }

    /**
     * @param params
     * @return
     */
    @Override
    public ResponseData<List<BusinessDetailVo>> getBusinessDetail(Map<String, Object> params) {
        return ResponseData.buildSuccessResponse(sysBusinessOrganizationMapper.getBusinessDetail(params));
    }

    @Override
    @Transactional
    public ResponseData<Boolean> addAppCity(AdminBusinessCityAddParam param) {
        String businessUuid = param.getBusinessUuid();
        //区域ID有值时 属于区域级开通 城市级与区域级不可并存开通
        boolean openArea = StringUtils.isNotEmpty(param.getAreaUuid());
        String cityUuid = openArea ? param.getAreaUuid() : param.getCityUuid();
        String cityAdCode = param.getCity();
        String areaAdcode = param.getArea();
        //查询业务
        SysBusinessDto sysBusinessDto = sysBusinessMapper.list(MapUtils.build("uuid", businessUuid)).get(0);
        if (sysBusinessDto != null) {
            //查询业务对应的车型
            Map<String, Object> carLevelParams = MapUtils.build(8);
            carLevelParams.put("businessType", sysBusinessDto.getType());
            carLevelParams.put("appid", param.getAppid());
            ResponseData<List<CarModelDto>> responseData = carModelService.list(carLevelParams);
            if (!responseData.isSuccess() || CollectionUtils.isEmpty(responseData.getData())) {
                return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, sysBusinessDto.getName() + "未添加车型，请先添加车型");
            }

            List<CarModelDto> carModelDtos = responseData.getData();
            //查询是否已经开通了该项业务
            Map<String, Object> build = MapUtils.build(4);
            build.put("organizationUuid", StringUtils.defaultIfNull(StringUtils.defaultIfNull(param.getUserCompanyUuid(),
                    param.getUserAgentUuid()), param.getAppid()));
            build.put("businessUuid", businessUuid);
            SysBusinessOrganizationDto sysBusinessOrganizationDto = sysBusinessOrganizationMapper.list(build).get(0);
            if (sysBusinessOrganizationDto == null) {
                return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, sysBusinessDto.getName() + "未开通业务，请先开通");
            }

            //查询该项业务是否已经开通了该城市
            Map<String, Object> sysBusinessCityParams = MapUtils.build(4);
            sysBusinessCityParams.put("businessOrganizationUuid", sysBusinessOrganizationDto.getUuid());
            sysBusinessCityParams.put("cityUuid", cityUuid);
            List<SysBusinessCityDto> cityDtoList = sysBusinessCityMapper.list(sysBusinessCityParams);
            if (CollectionUtils.isNotEmpty(cityDtoList)) {
                return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, sysBusinessDto.getName() + "业务下的该城市已经开通了");
            }

            //校验开通级别是否冲突
            ResponseData checkRsd = checkOpenLevel(openArea,param.getCity(),sysBusinessOrganizationDto.getUuid());
            if(!checkRsd.isSuccess()){
                return checkRsd;
            }

            try {
                // 如果需要新增区县到城市表的话 需要对应的城市编号
                if (CommonConstant.BUSINESS_TYPE_POOL != sysBusinessDto.getType() && openArea) {
                    String areaName = param.getAreaName();
                    String cityNo = PinyinUtils.chineseToPinYinSToUpperCase(areaName.substring(0, areaName.length() - 1));
                    // 如果是开通区县 并且该区县不在开通区县配置表中
                    // 则需要把区县提升到city同级 即在city表中加上area记录 并且要在区县开通配置表中加上一条记录
                    Map<String, Object> countParams = MapUtils.build();
                    countParams.put("areaUuid", cityUuid);
                    countParams.put("businessUuid", businessUuid);
                    if (sysOpenAreaConfigMapper.count(countParams) == 0) {
                        // 查询重复的城市编号
                        if (StringUtils.isNotEmpty(cityNo)) {
                            ResponseData<String> resData = sysCityService.getMaxCityNo(cityNo);
                            if (resData.isSuccess() && StringUtils.isNotEmpty(resData.getData()) && !cityNo.equals(resData.getData())) {
                                cityNo = cityNo + (Integer.valueOf(resData.getData().replace(cityNo, "")) + 1);
                            }
                        }
                        SysAreaDto sysAreaDto = sysAreaMapper.list(MapUtils.build("uuid", cityUuid)).get(0);
                        //区域编码不能与市级编码相同
                        if (sysAreaDto.getAreaID().equals(sysAreaDto.getFather())) {
                            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, sysAreaDto.getArea() + "区域编码与市级编码相同，请联系管理员");
                        }
                        //查询该区县是否已经开通升级为城市
                        List<SysCityDto> cityList = sysCityMapper.list(MapUtils.build("uuid", cityUuid));
                        if (CollectionUtils.isEmpty(cityList)) {
                            SysCityDto cityDto = new SysCityDto();
                            cityDto.setUuid(sysAreaDto.getUuid());
                            cityDto.setCity(sysAreaDto.getArea());
                            cityDto.setCityID(sysAreaDto.getAreaID());
                            cityDto.setCityNo(cityNo);
                            // 获取城市的上级ID
                            SysCityDto oldParentCityDto = sysCityMapper.list(MapUtils.build("uuid", param.getCityUuid())).get(0);
                            cityDto.setFather(oldParentCityDto.getFather());
                            cityDto.setFullPinyin(PinyinUtils.chineseToPinYinF(sysAreaDto.getArea()));
                            cityDto.setShortPinyin(PinyinUtils.chineseToPinYinS(sysAreaDto.getArea()));
                            //获取中心点
                            ResponseData<GeoVo> geo = locationService.geo(sysAreaDto.getArea());
                            if (geo.isSuccess() && geo.getData() != null) {
                                GeoVo geoVo = geo.getData();
                                cityDto.setCenter(geoVo.getLocation());
                            }
                            sysCityMapper.add(cityDto);
                        }
                        // 插入开通区县配置表
                        SysOpenAreaConfigDto sysOpenAreaConfigDto = new SysOpenAreaConfigDto();
                        sysOpenAreaConfigDto.setUuid(StringUtils.buildUUID());
                        sysOpenAreaConfigDto.setAreaUuid(cityUuid);
                        sysOpenAreaConfigDto.setArea(param.getAreaName());
                        sysOpenAreaConfigDto.setAreaID(areaAdcode);
                        sysOpenAreaConfigDto.setCreateOn(new Date());
                        sysOpenAreaConfigDto.setCreateBy(param.getUserUuid());
                        sysOpenAreaConfigDto.setBusinessUuid(businessUuid);
                        sysOpenAreaConfigMapper.add(sysOpenAreaConfigDto);
                    }
                }
                // 如果是开通区县的话 要先把区县加到城市表之后再查询城市表
                ResponseData<SysCityDto> resData = sysCityService.get(MapUtils.build("uuid", cityUuid));
                if (!resData.isSuccess() || resData.getData() == null) {
                    return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "获取城市数据失败");
                }
                SysCityDto sysCityDto = resData.getData();
                //新增开通城市
                SysBusinessCityDto businessCityDto = new SysBusinessCityDto();
                businessCityDto.setUuid(StringUtils.buildUUID());
                businessCityDto.setBusinessOrganizationUuid(sysBusinessOrganizationDto.getUuid());
                businessCityDto.setCityUuid(cityUuid);
                businessCityDto.setStatus(CommonConstant.STATUS_OPENED);
                businessCityDto.setCreateOn(new Date());
                sysBusinessCityMapper.add(businessCityDto);
                String cityCode = sysCityDto.getCityID();
                List<CarModelValuationDto> carModelsLevelDtoList = initCarModelValuationList(carModelDtos, param.getAppid(), sysBusinessDto.getType(), cityUuid, cityCode);
                ResponseData<Boolean> ajaxList = carModelValuationService.addBatch(carModelsLevelDtoList);
                if (!ajaxList.isSuccess()) {
                    return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, ajaxList.getMsg());
                }
                // 新增开通城市之后需要新增派单设置
                addAssignConfig(cityUuid, param.getUserUuid(), sysBusinessDto.getType());
                //新增对应区域的注册礼包
                addRegisterGift(sysCityDto, param.getAppid());
                //专车业务开通区县时修改电子围栏的所属城市
                if (CommonConstant.BUSINESS_TYPE_SPEC == sysBusinessDto.getType() && openArea) {
                    ResponseData<List<SysFenceDto>> listResponseData = sysFenceService.list(MapUtils.build("areaCode", cityAdCode));
                    if (responseData.isSuccess() && CollectionUtils.isNotEmpty(listResponseData.getData())) {
                        for (SysFenceDto sysFenceDto : listResponseData.getData()) {
                            sysFenceDto.setCityUuid(cityUuid);
                            sysFenceDto.setUpdateOn(new Date());
                            sysFenceService.edit(sysFenceDto);
                        }
                    }
                }
                return ResponseData.buildSuccessResponse(sysBusinessDto.getName() + "业务下的" + sysCityDto.getCity() + "城市开通成功", Boolean.TRUE);
            } catch (Exception e) {
                log.error("addAppCity error, openArea:{}, cityUuid:{}", openArea, cityUuid, e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }
        return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "城市开通失败");
    }

    /**
     * 校验开通级别
     */
    private ResponseData checkOpenLevel(boolean openArea,String cityId,String businessOrganizationUuid){
        Map<String,Object> paraMap = new HashMap<>();
        paraMap.put("businessOrganizationUuid", businessOrganizationUuid);
        paraMap.put("cityId",cityId);
        if(openArea){
            paraMap.put("openArea",1);
        }else{
            paraMap.put("openCity",1);
        }
        int resultCount = sysBusinessMapper.checkOpenLevel(paraMap);
        if(resultCount == 0){
            return ResponseData.buildSuccessResponse(null);
        }
        StringBuilder errMsg = new StringBuilder();
        errMsg.append(openArea?"该区域":"该城市").append("已存在").append(openArea?"城市":"区域").append("级别开通，请先关闭原有开通信息");
        return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE,errMsg.toString());
    }

    /**
     * 新增对应app城市下的优惠券注册礼包
     *
     * @param sysCityDto
     * @param appid
     */
    private void addRegisterGift(SysCityDto sysCityDto, String appid) {
        //1、查找注册礼包中对应的城市是否已经开通了
        if (marketingGiftMapper.isAddRegisterGift(sysCityDto.getUuid()) == null) {
            //2、插入t_marketing_gift表
            MarketingGiftDto marketingGiftDto = new MarketingGiftDto();
            String giftUuid = StringUtils.buildUUID();
            marketingGiftDto.setUuid(giftUuid);
            marketingGiftDto.setType(MarketingGiftDto.GIFT_REGISTER);
            marketingGiftDto.setCreateOn(new Date());
            marketingGiftDto.setAppid(appid);
            marketingGiftDto.setStatus(CommonConstant.STATUS_CLOSED);
            marketingGiftDto.setSendCity(sysCityDto.getUuid());
            marketingGiftDto.setSendCityName(sysCityDto.getCity());
            // 礼包初始化量为0
            marketingGiftDto.setTotalNumber(0);
            marketingGiftDto.setRemainNumber(0);
            String giftName = sysCityDto.getCity() + "注册大礼包";
            marketingGiftDto.setName(giftName);
            if (marketingGiftMapper.add(marketingGiftDto) > 0) {
                //插入统计渠道
                MarketingChannelDto marketingChannelDto = new MarketingChannelDto();
                marketingChannelDto.setUuid(StringUtils.buildUUID());
                marketingChannelDto.setName(giftName);
                marketingChannelDto.setGiftUuid(giftUuid);
                marketingChannelDto.setCreateOn(new Date());
                marketingChannelDto.setAppid(appid);
                marketingChannelMapper.add(marketingChannelDto);
            }
        }
    }


    /**
     * 新增开通城市之后默认初始化派单设置
     */
    private int addAssignConfig(String cityUuid, String userUuid, Integer businessType) {
        SysAssignConfigDto sysAssignConfigDto = new SysAssignConfigDto();
        sysAssignConfigDto.setUuid(StringUtils.buildUUID());
        sysAssignConfigDto.setDistrictUuid(cityUuid);
        sysAssignConfigDto.setBusinessType(businessType);
        sysAssignConfigDto.setCreateOn(new Date());
        sysAssignConfigDto.setCreateBy(userUuid);
        sysAssignConfigDto.setFixedRadius(new BigDecimal(10));
        sysAssignConfigDto.setFirstRadius(new BigDecimal(10));
        sysAssignConfigDto.setIncreaseRadius(new BigDecimal(1));
        sysAssignConfigDto.setMaxRadius(new BigDecimal(20));
        sysAssignConfigDto.setIntervalSecond(new BigDecimal(5));
        sysAssignConfigDto.setMaxWaitSecond(new BigDecimal(5 * 60));
        sysAssignConfigDto.setListenDownSecond(new BigDecimal(30));
        sysAssignConfigDto.setOperationStartTime("00:00:00");
        sysAssignConfigDto.setOperationEndTime("23:59:59");
        return sysAssignConfigMapper.add(sysAssignConfigDto);
    }


    /**
     * 初始化计价规则
     *
     * @param carModelDtos
     * @param appid
     * @param businessType
     * @param cityUuid
     * @param cityCode
     * @return
     */
    private List<CarModelValuationDto> initCarModelValuationList(List<CarModelDto> carModelDtos, String appid,
                                                                 Integer businessType, String cityUuid, String cityCode) {
        List<CarModelValuationDto> carModelValuationDtos = new ArrayList<>();
        ServerConfig.SystemBean systemBean = ApplicationConfig.SERVER_CONFIG.getSystem();
        for (CarModelDto carModelDto : carModelDtos) {
            //实时计费规则
            CarModelValuationDto carModelsModelRealDto = setCarModelValuationDto(carModelDto, cityUuid, cityCode, CommonConstant.TYPE_TIME_REAL_TIME, businessType);
            //预约计费规则
            CarModelValuationDto carModelsModelAppointDto = setCarModelValuationDto(carModelDto, cityUuid, cityCode, CommonConstant.TYPE_TIME_APPIONT, businessType);
            carModelValuationDtos.add(carModelsModelRealDto);
            carModelValuationDtos.add(carModelsModelAppointDto);
            //专车含有日租、半日租、接机、送机，其他业务只有实时、预约。
            if (businessType == CommonConstant.BUSINESS_TYPE_SPEC) {
                //新增日租计费规则
                if (systemBean.getSpecDailyRental()) {
                    CarModelValuationDto carModelsLevelDailyRentalDto = setCarModelValuationDto(carModelDto, cityUuid, cityCode, CommonConstant.TYPE_TIME_DAILY_RENTAL, businessType);
                    carModelValuationDtos.add(carModelsLevelDailyRentalDto);
                }
                //新增半日租计费规则
                if (systemBean.getSpecHalfDailyRental()) {
                    CarModelValuationDto carModelsLevelHalfDailyRentalDto = setCarModelValuationDto(carModelDto, cityUuid, cityCode, CommonConstant.TYPE_TIME_HALF_DAILY_RENTAL, businessType);
                    carModelValuationDtos.add(carModelsLevelHalfDailyRentalDto);
                }
                //新增送机计费规则
                if (systemBean.getSpecSendAirport()) {
                    CarModelValuationDto carModelsLevelSendAirportDto = setCarModelValuationDto(carModelDto, cityUuid, cityCode, CommonConstant.TYPE_TIME_SEND_AIRPORT, businessType);
                    carModelValuationDtos.add(carModelsLevelSendAirportDto);
                }
                //新增接机计费规则
                if (systemBean.getSpecMeetAirport()) {
                    CarModelValuationDto carModelsLevelMeetAirport = setCarModelValuationDto(carModelDto, cityUuid, cityCode, CommonConstant.TYPE_TIME_MEET_AIRPORT, businessType);
                    carModelValuationDtos.add(carModelsLevelMeetAirport);
                }
            }
        }
        return carModelValuationDtos;
    }

    /**
     * 设置计费规则
     *
     * @param carModelDto
     * @param cityUuid
     * @param cityCode
     * @param typeTime
     * @return
     */
    private CarModelValuationDto setCarModelValuationDto(CarModelDto carModelDto, String cityUuid, String cityCode,
                                                         int typeTime, Integer businessType) {
        CarModelValuationDto carModelValuationDto = new CarModelValuationDto();
        //以下为出租车、专车、快车通用字段
        carModelValuationDto.setUuid(StringUtils.buildUUID());
        carModelValuationDto.setCityUuid(cityUuid);
        carModelValuationDto.setCarModelUuid(carModelDto.getUuid());
        carModelValuationDto.setOrderTypeTime(typeTime);
        carModelValuationDto.setStatus(CommonConstant.STATUS_OPENED);
        carModelValuationDto.setAppid(carModelDto.getAppid());
        carModelValuationDto.setCreateOn(new Date());
        Integer sort = carModelDto.getSort();
        if (sort == null) {
            sort = carModelDto.getModelType();
        }
        carModelValuationDto.setFareType(getFareType(cityCode, carModelDto.getBusinessType(), typeTime, sort));
        //免费等待时间（超过这个时间才生效）
        carModelValuationDto.setFreeWaitTime(5);
        //超出等待时长费用（元/分钟）
        carModelValuationDto.setBeyondWaitFare(2d);
        //自己取消费用
        carModelValuationDto.setOwnCancelFare(0d);
        //系统取消费用
        carModelValuationDto.setSysCancelFare(0d);

        //因为现在出租车接口和专车走同一个接口，有使用到非出租车计费字段，临时处理
        if (businessType == CommonConstant.BUSINESS_TYPE_TAXI) {
            carModelValuationDto.setStartFare(0d);
            carModelValuationDto.setStartTrip(0d);
            carModelValuationDto.setStartDuration(0);
            carModelValuationDto.setBeyondTripFare(0d);
            carModelValuationDto.setBeyondTimeFare(0d);
            carModelValuationDto.setAssignDriverFare(0d);
            carModelValuationDto.setPremiumOneRate(1d);
            carModelValuationDto.setPremiumOneStart(DateUtils.parse("07:00:00", "HH:MM:SS"));
            carModelValuationDto.setPremiumOneEnd(DateUtils.parse("09:00:00", "HH:MM:SS"));
            carModelValuationDto.setPremiumTwoRate(1d);
            carModelValuationDto.setPremiumTwoStart(DateUtils.parse("17:00:00", "HH:MM:SS"));
            carModelValuationDto.setPremiumTwoEnd(DateUtils.parse("19:00:00", "HH:MM:SS"));
            carModelValuationDto.setNightTripFare(0d);
            carModelValuationDto.setHaulBackTrip(0d);
            carModelValuationDto.setHaulBackTripFare(0d);
        }

        //根据businessType及typeTime处理字段
        //出租车不包含以下费用
        if (businessType != CommonConstant.BUSINESS_TYPE_TAXI) {
            carModelValuationDto.setStartFare(10d);
            carModelValuationDto.setStartTrip(10d);
            carModelValuationDto.setStartDuration(30);
            carModelValuationDto.setBeyondTripFare(3d);
            carModelValuationDto.setBeyondTimeFare(3d);
            //日租、半日租不包含以下费用
            if (typeTime != CommonConstant.TYPE_TIME_DAILY_RENTAL && typeTime != CommonConstant.TYPE_TIME_HALF_DAILY_RENTAL) {
                carModelValuationDto.setAssignDriverFare(0d);
                carModelValuationDto.setPremiumOneRate(1d);
                carModelValuationDto.setPremiumOneStart(DateUtils.parse("07:00:00", "HH:MM:SS"));
                carModelValuationDto.setPremiumOneEnd(DateUtils.parse("09:00:00", "HH:MM:SS"));
                carModelValuationDto.setPremiumTwoRate(1d);
                //2高峰时段
                carModelValuationDto.setPremiumTwoStart(DateUtils.parse("17:00:00", "HH:MM:SS"));
                carModelValuationDto.setPremiumTwoEnd(DateUtils.parse("19:00:00", "HH:MM:SS"));
                carModelValuationDto.setNightTimeStart(DateUtils.parse("23:00:00", "HH:MM:SS"));
                carModelValuationDto.setNightTimeEnd(DateUtils.parse("06:00:00", "HH:MM:SS"));
                carModelValuationDto.setNightTripFare(0d);
                //远途里程（超过这个里程才生效）
                carModelValuationDto.setHaulBackTrip(20d);
                //远途里程费用（元/公里）
                carModelValuationDto.setHaulBackTripFare(4d);
            }
        }
        return carModelValuationDto;
    }

    /**
     * 获取运价码编号
     *
     * @param cityID
     * @param typeTrip
     * @param typeTime
     * @param sort
     * @return
     * @Description 规则：FT + 城市编码 + 业务编码 + 排序 + 订单时效性；共14位 ）
     * @author Zerrion
     */
    private String getFareType(String cityID, Integer typeTrip, Integer typeTime, Integer sort) {
        StringBuffer fareType = new StringBuffer();
        fareType.append("FT");
        fareType.append(cityID);
        //处理typeTrip，如果一位则补0，二位则不补0
        fareType.append(StringUtils.leftPad(typeTrip.toString(), 2, "0"));
        //处理modelType，如果一位则补0，二位则不补0
        fareType.append(StringUtils.leftPad(sort.toString(), 2, "0"));
        //typeTime，如果一位则补0，二位则不补0
        fareType.append(StringUtils.leftPad(typeTime.toString(), 2, "0"));
        return fareType.toString();
    }

    @Override
    public ResponseData<Boolean> removeAppCity(String businessUuid, String cityUuid) {
        SysBusinessDto sysBusinessDto = sysBusinessMapper.list(MapUtils.build("uuid", businessUuid)).get(0);
        if (sysBusinessDto == null) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "业务不存在", Boolean.FALSE);
        }
        int affectedRowCount = sysBusinessCityMapper.removeBusinessCity(businessUuid, cityUuid);
        if (affectedRowCount == 0) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "找不到对应的业务下的开通城市", Boolean.FALSE);
        }
        // 删除开通城市 同时伪删除对应的计价规则
        carModelValuationService.virtualDeleteModelsLevel(businessUuid, cityUuid);
        //这边判断所有业务中是否还包含着该城市，如果已经没有了，则删除对应城市的注册礼包
        removeRegisterGift(cityUuid);
        // 同步删除派单半径配置
        SysAssignConfigDto delParam = new SysAssignConfigDto();
        delParam.setBusinessType(sysBusinessDto.getType());
        delParam.setDistrictUuid(cityUuid);
        sysAssignConfigMapper.del(delParam);
        //同步删除该城市的计价规则
        PassengerRechargeCityDto passengerRechargeCityDto = new PassengerRechargeCityDto();
        passengerRechargeCityDto.setStatus(0);
        passengerRechargeCityDto.setCityUuid(cityUuid);
        passengerRechargeCityService.edit(passengerRechargeCityDto);
        //专车业务删除该城市下的电子围栏
        if (CommonConstant.BUSINESS_TYPE_SPEC == sysBusinessDto.getType()) {
            Map map = new HashMap();
            map.put("cityUuid", cityUuid);
            ResponseData<List<SysFenceDto>> responseData = sysFenceService.list(map);
            if (responseData.isSuccess() && CollectionUtils.isNotEmpty(responseData.getData())) {
                for (SysFenceDto fenceBean : responseData.getData()) {
                    sysFenceService.del(fenceBean);
                }
            }
        }
        //如果开通区域配置表中含有该区县升级为市级记录 先删除城市表中该区县的记录 即恢复该区域原先的父子关系 在删除区域配置表中的记录
        SysOpenAreaConfigDto sysOpenAreaConfigDto = sysOpenAreaConfigMapper.getByAreaUuidAndBusinessUuid(cityUuid, businessUuid);
        if (sysOpenAreaConfigDto != null) {
            Map<String, Object> params = new HashedMap(4);
            params.put("uuid", cityUuid);
            ResponseData<SysCityDto> responseData = sysCityService.get(params);
            //城市表中含有该区县 而且区域配置表中是否只有一条记录（即只有一个业务开通该区县） 则可以删除城市表中该区县的记录
            if (responseData.isSuccess() && responseData.getData() != null && sysOpenAreaConfigMapper.count(params) == 1) {
                sysCityService.del(responseData.getData());
            }
            sysOpenAreaConfigMapper.del(sysOpenAreaConfigDto);
        }
        return ResponseData.buildSuccessResponse("删除开通城市成功", Boolean.TRUE);
    }

    private void removeRegisterGift(String cityUuid) {
        //1、判断该城市还是否存在系统开通中
        if (sysBusinessCityMapper.isRemoveRegisterGift(cityUuid).isEmpty()) {
            //2、删除对应的城市开通礼包
            Map searchMap = MapUtils.build(4);
            searchMap.put("type", 1);
            searchMap.put("cityUuid", cityUuid);
            List<MarketingGiftDto> marketingGiftDtoList = marketingGiftMapper.list(searchMap);
            for (MarketingGiftDto marketingGiftDto : marketingGiftDtoList) {
                marketingGiftCityMapper.deleteBatch(marketingGiftDto.getUuid());
                marketingGiftMapper.del(marketingGiftDto);
            }
        }
    }

}